var addLindID = "addRuleRow";				//增加行按扭ID
var deleteLindID = "deleteAll";		//删除所有行按扭ID
var tableID = "ruleTable";				//表格ID
var timeData;
$(function(){
	
	$('#' + addLindID).click(function(){
		bindDetailList(null);
	});
	
	$('#' + deleteLindID).click(function(){
		$('#' + tableID).find('tbody').find('tr').not('.no-records-found').remove();
		
		if($('#' + tableID).find('tbody').children('tr').length == 0){
			var trStr = '<tr class="no-records-found">	'+
					    '   <td colspan="7" style="font-size:14px;">			'+
						'		单击底部“新增行”增加预约规则！		'+
						'	</td>						'+
						'</tr>';
			$('#' + tableID).find('tbody').append(trStr);
		}
	})
	
//	bindOrg1('orgSelect');
	bindOrg2("orgSelect", "", "");
	
	setItem1("bespeakItems","","");
	 $('#bespeakItems').select2({  
	        placeholder: "请选择行政许可项目",  
	        width:'100%'  
	    }); 
	
//	bindDict1("timeSelect","bespeak_period","");
	
	$.ajax({ 
			url: projectPath + "dict/getDictDetail.do",
			async : false,
			data: {"dictcode": 'bespeak_period'},
			dataType: "json",
			success: function(data){
				if(data.result == 1){   
					timeData = data.datas;
				}
	    	}
		});
	
	if(getUrlParam("ruleId") != null ){   //编辑操作
		var row = window.parent.rows;
		$("#ruleId").val(row.ruleid);
		$('#orgSelect').val(row.orgname);
		$('#orgSelect').attr('data', row.orgcode);
		$("[name='isPushlish'][value='"+row.ispushlish+"']").prop("checked", true);
		if(getUrlParam("copy") == 1){  //复制操作
			$("#ruleId").val('');
		}
		getRuleTime(row.ruleid);
	}
	
	
})

function getRuleTime(ruleId){
	$.ajax({ 
		url: basePath() + 'rule/getRuleTime.do',
		data: {"ruleId": ruleId},
		dataType: "json",
		success: function(data){	            						
			if(data.result == 1){ 
				data = data.datas;
				for(var i=0;i<data.length;i++)
					bindDetailList(data[i]);
			}
      	}
	});
}

function setItem1(selectID){
	var infoUrl = projectPath + "dict/getDictDetail.do";
	
	$.ajax({ 
		url: infoUrl,
		data: {"dictcode": "DM_XZXKXM"},
		dataType: "json",
		success: function(data){
			if(data.result == 1){
				var dataStr = data.datas;
				// 先清空控件数据
				$('#' + selectID).html(""); 

				var option = $("<option>").val("").text(""); 
				$('#' + selectID).append(option); 
				
				for (var i = 0; i < dataStr.length; i++) {
					var value = dataStr[i].itemcode;
					var text = dataStr[i].itemname;
					
					var option = $("<option>").val(value).text(text); 
					$('#' + selectID).append(option); 
				}	

				if(getUrlParam("copy") == null && getUrlParam("ruleId") != null ){ 
					$("#bespeakItems [value="+window.parent.rows.itemid+"]").prop("selected",true);
				}
			} else{
				$('#' + selectID).html("");
			}
    	}
	});
}

function setItem(selectID){
	var infoUrl = projectPath + "reserve/selectItem.do";
	$.ajax({ 
		url: infoUrl,
		data: {"itemno": ''},
		dataType: "json",
		success: function(data){
			if(data.result == 1){   				
				var dataStr = data.datas;
				// 先清空控件数据
				$('#' + selectID).html(""); 

				var option = $("<option>").val("").text(""); 
				$('#' + selectID).append(option); 
				
				for (var i = 0; i < dataStr.length; i++) {
					var value = dataStr[i].itemno;
					var text = dataStr[i].itemname;
					
					var option = $("<option>").val(value).text(text); 
					$('#' + selectID).append(option); 
				}	

				if(getUrlParam("copy") == null && getUrlParam("ruleId") != null ){ 
					$("#bespeakItems [value="+window.parent.rows.itemid+"]").prop("selected",true);
				}
				
			}else{
				$('#' + selectID).html("");
			}
    	}
	});
	
}

function getUrlParam(name){ //获取url参数
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
}

function addOption(selectID){

	// 先清空控件数据
	$('#' + selectID).empty(); 

	var option = $("<option>").val("").text(""); 
	$('#' + selectID).append(option); 
	
	for (var i = 0; i < timeData.length; i++) {
		var value = timeData[i].itemname;
		var text = timeData[i].itemname;
		
		var option = $("<option>").val(value).text(text); 
		$('#' + selectID).append(option); 
	}	
	
	//选中下拉列表的值
	//if(selectdata != ""){
//		$('#' + selectID).val(selectdata);
//	}
	
}

function bindDetailList(data){
	$('#' + tableID).find('.no-records-found').remove();
	
	var index = 1;
	if($('#' + tableID).find('tbody').find('tr').length > 0){
		index = parseInt($('#' + tableID).find('tbody').find('tr:last').find('.serialnumber').val()) + 1;
	}
	
    
    var reservenum = "";
    var timerange = "";
    
	var ifenabledStr = 'checked="checked"';
    if(data != null){
    	if(data.ifenabled == 0)
    		ifenabledStr = '';
    	
    	reservenum = data.reservenum;
    	timerange = data.timerange;
    }
        	
	
	var trStr = '<tr id="tr_'+ index +'" class="data">'+
				'<form class="form-horizontal dictDetailForm" id="ruleDetailForm_'+ index +'">'+
			    '    <td>'+
			    '    	<input type="number" class="form-control serialnumber" style="text-align: center;" value="'+ index +'" name="serialnumber" />'+
			    '    </td>'+
			    '    <td style="width:200px;">'+
			    '       <input type="number"  class="form-control" name="reservenum" min="0" value="'+reservenum+'" placeholder="请输入预约人数限制"></input>'+
		        '	</td>'+
			    '    <td>'+
			    '    <select class="form-control" name="timerange" id="timeSelect'+index+'" value="'+ timerange +'" placeholder="请选择预约时间段"></select>'+
			    '    </td>'+
			    '    <td>'+
    			'		<button type="button" class="Delete btn btn-danger btn-sm" onclick="deleteDetailLine(\'tr_'+ index +'\');" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span></button>'+
			    '    </td>'+
			    '</form>'+
			    '</tr>';
	
	$('#' + tableID).find('tbody').append(trStr);
	addOption('timeSelect'+index);
	$("#timeSelect"+index+" [value='"+timerange+"']").prop("selected",true);
}

function deleteDetailLine(trId){
	$('#' + trId).remove();
	
	if($('#' + tableID).find('tbody').children('tr').length == 0){
		var trStr = '<tr class="no-records-found">	'+
				    '   <td colspan="7" style="font-size:14px;">			'+
					'		单击底部“新增行”增加预约规则！		'+
					'	</td>						'+
					'</tr>';
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function save(){  //保存
	var ruleData = $("#ruleForm").serializeObject();
	var b=$("#bespeakItems").val();
	ruleData.itemname=$("#bespeakItems").find("option[value="+b+"]").html();
	ruleData.orgcode=$("#orgSelect").attr("data");
	var ruleDetailData = $('#ruleDetailForm').serializeObjectArray();
	for(var i=0;i<ruleDetailData.length;i++){
	  delete ruleDetailData[i]["serialnumber"];
	}
	var ruleDetail = {};
	ruleDetail['row'] = ruleDetailData;
	ruleData['table'] = ruleDetail;
	if (!check(ruleData))
		return true;		
	var ruleId=$("#ruleId").val();
	if(ruleId==""){
		$.ajax({ 
			method: 'post',
			url: basePath() + 'rule/insertRule.do',
			data: JSON.stringify(ruleData),
			dataType: "json",
	        contentType: "application/json",
			success: function(data){	
		    	window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info,{
		    		onOk:function(v){
		    			if(data.result == 1){
				    		parent.$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
				    		parent.$('#modalMenu').modal('hide');
				    	}
					}
		    	});
		    	
	      	}
		})
	}else{
		$.ajax({ 
			method: 'post',
			url: basePath() + 'rule/updateRule.do',
			data: JSON.stringify(ruleData),
			dataType: "json",
	        contentType: "application/json",
			success: function(data){	
				window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.info,{
		    		onOk:function(v){
		    			if(data.result == 1){
				    		parent.$('#bookingTable').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
				    		parent.$('#modalMenu').modal('hide');
				    	}
					}
		    	});
	      	}
		})
	}
}


function check(data){	//数据校验
	var result = true;
	
	if($("#orgSelect").val() == ""){
		window.wxc.xcConfirm('所属机构不能为空！', window.wxc.xcConfirm.typeEnum.info);
		return false;
	}
	
	if($("#bespeakItems").val() == ""){
		window.wxc.xcConfirm('行政许可项目不能为空！', window.wxc.xcConfirm.typeEnum.info);
		return false;
	}

	if($('#ruleTable').find('tbody').find('tr').not('.no-records-found').length == 0){
		window.wxc.xcConfirm('请增加<span style="color:red;"><strong>预约明细</strong></span>的行数据！', window.wxc.xcConfirm.typeEnum.info);
		return false;
	}
	
	
	var mustStr = "reservenum,timerange";
	
	var strMsg = "";
	var mustStrs = mustStr.split(',');
	for(var i=0; i<mustStrs.length; i++){
		var obj = $('[name="'+mustStrs[i]+'"]');
		if(obj.val() == ""){
			strMsg += obj.attr("placeholder") + "！<br />";
			
			result = false;
		}
	}
	
	var timerange = $("[name='timerange']");
	var time=new Array(timerange.length);
	for(i=0;i<timerange.length;i++){
		time[i]=$(timerange[i]).val();//获取value值
	}

	 time=time.sort();
	 
	 for(var i=0;i<time.length;i++){  //判断预约时间是否重复
	 
	 if (time[i]==time[i+1]){
	 
	  strMsg="预约时间段："+time[i]+"重复，请重新选择!";
	  result = false;
	 }
	 }
	 

	if(strMsg != ""){
		window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.info);
	}
	
	
	
	return result;
}







